package com.sdry.web.controller.zc;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.sdry.model.inventoryInfoOnlyCountRejects.InventoryInfoOnlyCountRejects;
import com.sdry.model.jyy.Receive;
import com.sdry.model.jyy.ReceiveDetail;
import com.sdry.model.lz.Customer;
import com.sdry.model.lz.Warehouse;
import com.sdry.model.zc.ZcGeneralQueryEntity;
import com.sdry.model.zc.ZcInventoryInfoEntity;
import com.sdry.model.zc.ZcSysUserEntity;
import com.sdry.service.inventoryInfoOnlyCountRejects.InventoryInfoOnlyCountRejectsService;
import com.sdry.service.jyy.ReceiveDetailService;
import com.sdry.service.jyy.ReceiveService;
import com.sdry.service.jyy.UpService;
import com.sdry.service.lz.CustomerService;
import com.sdry.service.lz.WarehouseService;
import com.sdry.service.zc.ZcInventoryManagementService;
import com.sdry.service.zc.ZcSimplificationInService;
import com.sdry.utils.DateUtil;
import com.sdry.utils.ExcelUtils;
import com.sdry.utils.ResponseUtil;

/**
 * 精简入库
 * @ClassName 
 * @Description 
 * @Author zc
 * @Date 2019年8月6日 上午11:20:33
 * @Version 1.0
 */
@Controller
@RequestMapping("simplificationIn")
public class ZcSimplificationInController {
	@Resource
	private ZcInventoryManagementService zcInventoryManagementService;
	@Resource
	private ZcSimplificationInService zcSimplificationInService;
	@Resource
	private UpService upService;
	@Resource
	private ReceiveDetailService receiveDetailService;
	@Resource
	private ReceiveService receiveService;
	@Resource
	private InventoryInfoOnlyCountRejectsService inventoryInfoOnlyCountRejectsService;
	@Resource
	private WarehouseService warehouseService;
	@Resource
	private CustomerService  customerService;
	/**
	 * 进入精简入库页面
	 * @param httpSession
	 * @return
	 */
	@RequestMapping("enterSimplificationInPage")
	public ModelAndView enterSimplificationInPage(Model model,HttpSession session,HttpServletResponse response){
		ZcSysUserEntity staf = (ZcSysUserEntity) session.getAttribute("user");
		if(staf.getRoleId().equals("20010,")) {
			//客户
			Customer customer=customerService.queryCustomerlxrById(staf.getCustomer_id());
			model.addAttribute("cname", customer.getCustomer_name());
			model.addAttribute("cid", staf.getCustomer_id());
			model.addAttribute("lname", customer.getContacts_name());
			Warehouse warehouse=warehouseService.queryWarehouse();
			model.addAttribute("charger", warehouse.getCharger());
			model.addAttribute("chargertel", warehouse.getChargertel());
			ZcGeneralQueryEntity zcGeneralQueryEntity = new ZcGeneralQueryEntity();
			//查询所有供应商
			List<Customer> allCustomerList = zcInventoryManagementService.selectAllCustomerList(zcGeneralQueryEntity);
			ModelAndView mav = new ModelAndView();
			mav.addObject("allCustomerList",allCustomerList);
			mav.setViewName("/zc/warehouse/simplificationIn2");
			return mav;
		} else {
			ZcGeneralQueryEntity zcGeneralQueryEntity = new ZcGeneralQueryEntity();
			//查询所有供应商
			List<Customer> allCustomerList = zcInventoryManagementService.selectAllCustomerList(zcGeneralQueryEntity);
			Warehouse warehouse=warehouseService.queryWarehouse();
			model.addAttribute("charger", warehouse.getCharger());
			model.addAttribute("chargertel", warehouse.getChargertel());
			ModelAndView mav = new ModelAndView();
			mav.addObject("allCustomerList",allCustomerList);
			mav.setViewName("/zc/warehouse/simplificationIn");
			return mav;
		 }
	}
	/**
	 * 新增入库单
	 * @param receive
	 * @param httpServletResponse
	 */
	@RequestMapping("insertSimplificationIn")
	public void insertSimplificationIn(Receive receive, HttpServletResponse response,HttpSession httpSession){
		ZcSysUserEntity su = (ZcSysUserEntity)httpSession.getAttribute("user");
		receive.setCreateName(su.getId()+"");
		
		receive.setSendDate(receive.getCreateDate());
		
		//此字段已被占用(标识为精简入库)
		//receive.setRemark("-1");
		receive.setIsSimple(1);
		int affact = zcSimplificationInService.insertSimplificationIn(receive);
		try {
			ResponseUtil.write(response, affact);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 新增详情
	 * @param receiveDetail
	 * @param response
	 */
	@RequestMapping("insertDetails")
	public void insertDetails(ReceiveDetail receiveDetail, HttpServletResponse response){
		int affact = zcSimplificationInService.insertDetails(receiveDetail);
		try {
			ResponseUtil.write(response, affact);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 条件查询入库单列表
	 * @param zcGeneralQueryEntity
	 * @param response
	 */
	@RequestMapping("selectSimplificationInList")
	public void selectSimplificationInList(ZcGeneralQueryEntity zcGeneralQueryEntity,HttpServletResponse response){
		if(zcGeneralQueryEntity.getStrWhere() == null){
			zcGeneralQueryEntity.setStrWhere(" r.isSimple = 1 and ");
		}
		List<Receive> simplificationInList = zcSimplificationInService.selectSimplificationInList(zcGeneralQueryEntity);
		int count = zcSimplificationInService.countSimplificationInList(zcGeneralQueryEntity);
		JSONObject jsonObject = new JSONObject();
		JsonConfig jsonConfig = new JsonConfig();
		JSONArray jsonArray = JSONArray.fromObject(simplificationInList, jsonConfig);
		jsonObject.put("code", 0);
		jsonObject.put("data", jsonArray);
		jsonObject.put("count", count);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 批量删除
	 * @param response
	 * @param idArr
	 */
	@RequestMapping("deleteSimplificationInByNumber")
	public void deleteSimplificationInByNumber(HttpServletResponse response, @RequestParam("receiveNumber[]") String[] receiveNumber){
		int affectRow = 0;
		for (int i = 0; i < receiveNumber.length; i++) {
			ZcGeneralQueryEntity zcGeneralQueryEntity = new ZcGeneralQueryEntity();
			String receiveNumberNew  = "'"+receiveNumber[i]+"'";
			zcGeneralQueryEntity.setStrWhere(" receive_number = "+receiveNumberNew);
            affectRow = zcSimplificationInService.deleteSimplificationInByNumber(zcGeneralQueryEntity);
        }
		try {
			ResponseUtil.write(response, affectRow);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	//----------------------------------------------------jyy------------------------------------------------------------
	
	/**
	 * 收货提交(计数)
	 * @param receiveNumber 收货单号
	 * @param response 响应
	 * @throws Exception 异常
	 */
	@RequestMapping("/submitReceipt")
	public void submitReceipt(String receiveNumber, HttpServletResponse response, HttpSession httpSession) throws Exception{
		//初始化影响行数
		int affact1 = 0;
		Long affact = 0L;
		//获取session中的用户信息
		ZcSysUserEntity user = (ZcSysUserEntity)httpSession.getAttribute("user");
		
		//根据收货单号查询收货单明细
		ReceiveDetail param = new ReceiveDetail();
		param.setReceiveNumber(receiveNumber);
		List<ReceiveDetail> receiveDetailList = receiveDetailService.queryAllByMution(param);
		String date = DateUtil.dateFormat3();
		//遍历修改
		for (ReceiveDetail receiveDetail : receiveDetailList) {
			/*==================修改收货详细表信息==========*/
			receiveDetail.setCodeNum(receiveDetail.getTotalNum());
			affact1 = receiveDetailService.update(receiveDetail);
			/*====================添加库存=======================*/
			int number = receiveDetail.getCodeNum();
			ZcInventoryInfoEntity zcInventoryInfoEntity = upService.selectByMid2(receiveDetail.getMid() + "", receiveDetail.getPici());
			//1.如果查到
			if (zcInventoryInfoEntity != null) {
				int mNum = zcInventoryInfoEntity.getmNum();
				//1.如果是精准码,只存入总数
				mNum = number + mNum;
				//总数量（个数）
				zcInventoryInfoEntity.setmNum(mNum);
				affact = upService.editStockOnlyCount(zcInventoryInfoEntity);
			} else {
				ZcInventoryInfoEntity zcInventoryInfoEntity1 = new ZcInventoryInfoEntity();
				zcInventoryInfoEntity1.setMid(receiveDetail.getMid());
				zcInventoryInfoEntity1.setmNum(receiveDetail.getCodeNum());
				zcInventoryInfoEntity1.setmBatch(receiveDetail.getPici());
				zcInventoryInfoEntity1.setEnterPerson(user.getId());
				zcInventoryInfoEntity1.setEnterDate(date);
				affact = upService.insertStockOnlyCount(zcInventoryInfoEntity1);
			}
			
			//添加精简不良品
			int ngNum = receiveDetail.getNgNum();
			InventoryInfoOnlyCountRejects inventoryInfoOnlyCountRejects = new InventoryInfoOnlyCountRejects();
			inventoryInfoOnlyCountRejects.setMid(receiveDetail.getMid());
			inventoryInfoOnlyCountRejects.setMbatch(receiveDetail.getPici());
			List<InventoryInfoOnlyCountRejects> inventoryInfoOnlyCountRejectss = inventoryInfoOnlyCountRejectsService.queryAllByMution(inventoryInfoOnlyCountRejects);
			if(inventoryInfoOnlyCountRejectss.size() > 0){
				inventoryInfoOnlyCountRejects = inventoryInfoOnlyCountRejectss.get(0);
				int mNum = inventoryInfoOnlyCountRejects.getMnum();
				//1.如果是精准码,只存入总数
				mNum = ngNum + mNum;
				//总数量（个数）
				inventoryInfoOnlyCountRejects.setMnum(mNum);
				Integer updateCount = inventoryInfoOnlyCountRejectsService.update(inventoryInfoOnlyCountRejects);
				affact = updateCount.longValue();
			}else{
				inventoryInfoOnlyCountRejects.setMnum(receiveDetail.getNgNum());
				inventoryInfoOnlyCountRejects.setEnterperson(user.getId());
				inventoryInfoOnlyCountRejects.setEnterdate(date);
				affact = inventoryInfoOnlyCountRejectsService.insert(inventoryInfoOnlyCountRejects);
			}
			inventoryInfoOnlyCountRejects = null;
		}

		//更改一级状态  --为已收货
		Receive receive = new Receive();
		receive.setReceiveNumber(receiveNumber);
		receive.setIsSimple(1);
		List<Receive> receives = receiveService.allByMution(receive);
		
		if(receives.size()  > 0) {
			Receive receive2 = receives.get(0);
			receive2.setState(1);
			receive2.setReceiveDate(DateUtil.dateFormat1());
			receive2.setReceiveName(user.getId()+"");
			receive2.setSendCompany(null);
			//回收容器数量
			//receive2.setSureName(sure_name);
			receiveService.update(receive2);
		}
		ResponseUtil.write(response, affact);
	}
	/**
     * 导出Excel
     * @param response
	 * @throws UnsupportedEncodingException 
     * @throws Exception
     */
    @RequestMapping("/doExportall")

    public void doExportall(HttpServletResponse response, HttpServletRequest request, String strWhere,ZcGeneralQueryEntity zcGeneralQueryEntity) throws UnsupportedEncodingException{
		if(zcGeneralQueryEntity.getStrWhere() == null){
			zcGeneralQueryEntity.setStrWhere("");
		}
		
    	zcGeneralQueryEntity.setPage(1);
	    zcGeneralQueryEntity.setLimit(10000);
	    List<Receive> simplificationInList = zcSimplificationInService.selectSimplificationInList(zcGeneralQueryEntity);
		ZcGeneralQueryEntity zcGeneralQueryEntity2=new ZcGeneralQueryEntity();
        List<List<String>> lists = zhuanlist(simplificationInList,zcGeneralQueryEntity2);
        ExcelUtils.export("精简入库所有数据",namess(), response, lists);
    }

    public List<String> namess() {
        List<String> list = new ArrayList<>();
        list.add("序号");
        list.add("入库单号");
        list.add("供应商");
        list.add("发货日期");
        list.add("发货人");
        list.add("创建人");
        list.add("客户单号");
        list.add("订单状态");
       
       return list;
    }

    public List<List<String>> zhuanlist ( List<Receive> simplificationInList,  ZcGeneralQueryEntity zcGeneralQueryEntity2) throws UnsupportedEncodingException{
		
		{
        List<List<String>> lists = new ArrayList<>();
        int count=0;
           for (Receive inventoryOrder : simplificationInList) {
		    List<String> list = new ArrayList<>();
		    ++count;
		    list.add(String.valueOf(count));
		    list.add(inventoryOrder.getReceiveNumber());
		    list.add(inventoryOrder.getSendCompany());

				/*
				 * SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm"); if(null !=
				 * inventoryOrder.getCreateDate()){ String
				 * str=sdf.format(inventoryOrder.getCreateDate()); list.add(str); }else{
				 * list.add(""); }
				 */
		    list.add(inventoryOrder.getCreateDate());
		    list.add(inventoryOrder.getSendName());
		    list.add(inventoryOrder.getCreateName());
            
		    list.add(inventoryOrder.getSendNumber());
		    if(inventoryOrder.getState()==0) {
		    	list.add("未收货");
		    }else {
		    	list.add("已收货");
		    }
		     lists.add(list);

		    List<String> listd = new ArrayList<>();
            listd.add("入库单号为"+inventoryOrder.getReceiveNumber()+"的入库单详情表");
            lists.add(listd);
            List<String> listn = new ArrayList<>();
            listn.add("序号");
            listn.add("中文名称");
            listn.add("产品码");
            listn.add("包装数量");
            listn.add("批次");
            listn.add("发货良品数(个)");
            listn.add("发货不良品数(个)");
            listn.add("收货良品数(个)");
            listn.add("收货不良品数(个)");
            lists.add(listn);
            ReceiveDetail param1=new ReceiveDetail();
            param1.setLimit(10000);
        	param1.setPage(1);
        	param1.setReceiveNumber(inventoryOrder.getReceiveNumber());
        	List<ReceiveDetail> listds = receiveDetailService.findPageByMution(param1);
           for (ReceiveDetail detail : listds) {
           	 List<String> list1 = new ArrayList<>();
           	 list1.add(String.valueOf(detail.getId()));
             
                list1.add(detail.getMateriel_name());
                list1.add(detail.getBrevity_num());
                list1.add(detail.getPacking_quantity());
                list1.add(detail.getPici());
                list1.add(String.valueOf(detail.getTotalNum()));
                list1.add(String.valueOf(detail.getNgNum()));
                list1.add(String.valueOf(detail.getCodeNum()));
                list1.add(String.valueOf(detail.getNgNum()));
                lists.add(list1);
                list1 = null;
			}
            list = null;
        }
        return lists;
    }
}
}
